#!/usr/bin/env python
import sys
sys.path.append(".")

def build_auth_header(db_user, db_password):
    """
    Build an authorization header
    """
    import base64
    base64string = base64.encodestring('%s:%s' % (db_user, db_password))[:-1]
    return "Basic %s" % base64string

def login(db_host, db_port, base_url, enable_ssl):
    """
    Get the username/password combo

    @return: (db_user, db_password)
    """
    from getpass import getpass
    connected = False
    if enable_ssl:
        from httplib import HTTPSConnection as Connection
    else:
        from httplib import HTTPConnection as Connection

    while not connected:
        db_user = raw_input("Username: ")
        db_password = getpass()
        headers = {}
        headers["Authorization"] = build_auth_header(db_user, db_password)
        connection = Connection(db_host, db_port)
        connection.request("GET", base_url, None, headers)
        resp = connection.getresponse()
        if resp.status == 200:
            connected = True
        else:
            print "Login Failed: %s" % resp.status

    return (db_user, db_password)

def main(options, args):
    import boto

    # Config
    boto.config.set("DB", "db_type", "XML")
    boto.config.set("DB", "db_host", options.db_host)
    boto.config.set("DB", "enable_ssl", str(options.enable_ssl))
    boto.config.set("DB", "db_port", options.db_port)

    (db_user, db_password) = login(options.db_host, options.db_port, options.base_url,  options.enable_ssl)
    boto.config.set("DB", "db_user", db_user)
    boto.config.set("DB", "db_passwd", db_password)

    import readline
    import code
    session = {}

    import sys
    sys.ps1 = "\x01\x1b[34m\x1b[1m\x02>>> \x01\x1b[0m\x02"
    sys.ps2 = "... "

    from vermouth.resources.project import Project
    Project._manager.db_name = options.base_url +"/projects"
    session['Project'] = Project

    from vermouth.resources.ticket import Ticket
    Ticket._manager.db_name = options.base_url + "/tickets"
    session['Ticket'] = Ticket

    from boto_web.resources.user import User
    User._manager.db_name = options.base_url + "/users"
    session['User'] = User

    code.interact(local=session, banner="Vermouth interactive console")

if __name__ == "__main__":
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option("--host", dest="db_host", help="Appserver Hostname", default="localhost")
    parser.add_option("--port", dest="db_port", help="Appserver Port", default="80")
    parser.add_option("--base-url", dest="base_url", help="Appserver data base url", default="/data")
    parser.add_option("--enable-ssl", dest="enable_ssl", action="store_true", help="Indicates we are using SSL for the appserver communication", default=False)
    parser.add_option("-d", "--debug", dest="debug", action="store_true", help="Enable Debug mode, this will dump all requests and responses to STDOUT", default=False)

    (options, args) = parser.parse_args()
    main(options, args)
